<template>
  <div id="app" class="container mx-auto p-4">
    <el-dialog :title="dialogTitle" v-model="dialogVisible">
      <el-form :model="tableform">
        <el-form-item label="标题">
          <el-input v-model="tableform.title"></el-input>
        </el-form-item>
        <el-form-item label="内容">
          <el-input type="textarea" v-model="tableform.content" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="课程号">
          <el-input v-model="tableform.cno"></el-input>
        </el-form-item>
        <el-form-item label="开始时间" v-if="dialogType !== 'edit'">
          <el-date-picker v-model="tableform.time_start" type="datetime" placeholder="选择日期时间"></el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" v-if="dialogType !== 'edit'">
          <el-time-picker v-model="tableform.time_end" placeholder="选择时间"></el-time-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="dialogOk">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <h1 class="text-2xl font-bold mb-4">收件箱</h1>

    <el-input placeholder="搜索邮件" class="w-full mb-4" v-model="searchTitle"></el-input>
    <el-button type="primary" @click="getInfo">搜索</el-button>
    <el-button type="success" @click="handleAdd">添加通知</el-button>
    <el-table :data="info">
      <el-table-column prop="title" label="标题"></el-table-column>
      <el-table-column prop="content" label="内容"></el-table-column>
      <el-table-column prop="time_start" label="发布时间" width="180">
        <template #default="scope">
          <span>{{ formatDate(scope.row.time_start) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="180">
        <template #default="{ row }">
          <el-button type="primary" size="small" :icon="Edit" @click="handleEdit(row)">编辑</el-button>
          <el-button type="danger" size="small" :icon="Delete" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        background
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 20]"
        :total="total"
        layout="prev, pager, next, sizes"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>
</template>
<script setup>
import axios from "axios";
import { onMounted, ref } from "vue";
import { Delete, Edit } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";

const info = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const searchTitle = ref('');
const dialogVisible = ref(false);
const dialogTitle = ref('');
const dialogType = ref('');
const tableform = ref({});
const oldForm = ref({});

onMounted(() => {
  getInfo();
});

const getInfo = () => {
  axios.get('http://localhost:8080/inform', {
    params: {
      page: currentPage.value,
      size: pageSize.value,
      title: searchTitle.value
    }
  }).then(response => {
    info.value = response.data.records;
    total.value = response.data.total;
  }).catch(error => {
    console.error("Error fetching informations:", error);
  });
};

const handleCurrentChange = (pageNum) => {
  currentPage.value = pageNum;
  getInfo();
};

const handleSizeChange = (newPageSize) => {
  pageSize.value = newPageSize;
  getInfo();
};

const formatDate=(timestamp)=> {
  const date = new Date(timestamp);
  return `${date.getFullYear()}-${date.getMonth()+1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
}

const handleEdit = (row) => {
  dialogTitle.value = '编辑通知';
  dialogType.value = 'edit';
  tableform.value = { ...row };
  dialogVisible.value = true;
};

const handleDelete = (row) => {
  ElMessageBox.confirm(
      `您确定要删除通知【${row.title}】吗?`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    const id = encodeURIComponent(row.id); // 使用 id 作为主键
    axios.delete(`http://localhost:8080/inform/${id}`)
        .then(() => {
          ElMessage({
            type: 'success',
            message: '删除成功!'
          });
          getInfo(); // 刷新列表
        }).catch(error => {
      console.error("Error deleting information:", error);
    });
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除'
    });
  });
};

const handleAdd = () => {
  dialogTitle.value = '添加通知';
  dialogType.value = 'add';
  tableform.value = {}; // 清空表单
  dialogVisible.value = true;
};

const dialogOk = () => {
  if (dialogType.value === 'add') {
    axios.post('http://localhost:8080/inform', tableform.value)
        .then(() => {
          ElMessage({
            type: 'success',
            message: '添加成功！'
          });
          dialogVisible.value = false;
          getInfo(); // 刷新列表
        }).catch(error => {
      console.error("Error adding information:", error);
    });
  } else if (dialogType.value === 'edit') {
    axios.put(`http://localhost:8080/inform`,tableform.value )
        .then(() => {
          ElMessage({
            type: 'success',
            message: '修改成功！'
          });
          dialogVisible.value = false;
          getInfo(); // 刷新列表
        }).catch(error => {
      console.error("Error updating information:", error);
    });
  }
};
</script>